package jal4eclipse.jal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class JALV2Compiler {
	private JALV2Compiler() {
	}

	public static JALCompileResult compile(String compilerPath,String mainFile, String libPath, String options) {
		
		final StringBuffer res = new StringBuffer();
		final ArrayList errors = new ArrayList();
		String commandLine = compilerPath +" -s "+libPath;
		if ((options!= null)&&(!"".equals(options))) {
			commandLine+=" "+options;
		}
		commandLine += " "+mainFile;
		Process externalProcess;
		
		try {	    
			
		   externalProcess = Runtime.getRuntime().exec ( commandLine );
		  // buffering is recomended, so...
		  final BufferedReader std = new BufferedReader ( new InputStreamReader( externalProcess.getInputStream() ) );
		  final BufferedReader stdErr = new BufferedReader ( new InputStreamReader( externalProcess.getErrorStream() ) );
			
		  Thread t1 = new Thread(new Runnable(){
			public void run() {
				String oneLine ;
				try {
					Pattern pattern = Pattern.compile("(.*):(\\d+):(.*)$");
					while ((oneLine = std.readLine())!= null) {
						res.append(oneLine+"\n");
					    Matcher matcher = pattern.matcher(oneLine);
					    if(matcher.matches()) {
							JALErrors err = new JALErrors();
							String file = matcher.group(1);
							String line = matcher.group(2);
							String msg = matcher.group(3);
							err.setFile(file);
							err.setLine(Integer.parseInt(line));
							err.setMessage(msg);
							errors.add(err);
					    }
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		  });
		  Thread t2 = new Thread(new Runnable(){
				public void run() {
					String oneLine ;
					try {
						while ((oneLine = stdErr.readLine())!= null) {
							res.append(oneLine+"\n");
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			  });
		  
		  t1.start();
		  t2.start();
		  while(t1.isAlive());
		  while(t2.isAlive());
		} catch ( Exception ex ) {
		  ex.printStackTrace();
		} 
		
		JALCompileResult result = new JALCompileResult();
		result.setCommandLine(commandLine);
		result.setResult(res.toString());
		result.setErrors((JALErrors[]) errors.toArray(new JALErrors[errors.size()]));
		
		// Debug
		
		for (int i = 0;i<result.getErrors().length;i++) {
			JALErrors err = result.getErrors()[i];
			
		}
		
		return result;
	}

	public static void main(String[] args) {
		String COMPILER_PATH = "C:\\PICjal\\JAL\\Compiler\\Jalv2.exe";
		String mainFile = "D:\\eclipse\\runtime-EclipseApplication\\TestJAL\\test.jal";
		String libpath = "C:\\PICjal\\JAL\\Libraries";
		JALCompileResult res = JALV2Compiler.compile(COMPILER_PATH, mainFile, libpath,
				"-Wno-all");
		System.out.println(res.getCommandLine());
		System.out.println("Completed");
		for (int i = 0;i<res.getErrors().length;i++) {
			JALErrors err = res.getErrors()[i];
			System.out.println(err.getLine());
		}
	
	}

}
